package com.store.app.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.store.app.ExitApplication;
import com.store.app.R;
import com.store.app.adapter.GoodsShowsAdapter;
import com.store.app.bean.GoodsListBean;
import com.store.app.fragment.GoodsFragment;
import com.store.app.fragment.KeyboardFragment;
import com.store.app.fragment.ScanFragment;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.utils.MoneyUtil;
import com.store.app.utils.SettingData;
import com.store.app.utils.Utils;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/3/1.
 * 新的收银页面
 */
public class CashierActivity extends FragmentActivity implements View.OnClickListener,IOnHttpListener{

    private Fragment goodsFragment;                 //快捷商品Fragment
    private Fragment keyboardFragment;              //数字键盘Fragment
    private Fragment scanFragment;                  //扫描二维码Fragment

    private static TextView tvPayMoney,tv_right;                    //需要支付的总价钱
    private FragmentManager fm;
    private FragmentTransaction ft;
    private TextView llChangeFragment;          //点击切换不同的Fragment
    private int CurrentFragmentIndex = 4;           //初始化fragment当前下标
    private static ListView lvGoodsShows;                  //商品列表
    public static List<GoodsListBean> goodsListBeanList = new ArrayList<GoodsListBean>();  //商品列表数据
    private static GoodsShowsAdapter goodsShowsAdapter;    //商品列表适配器
    private static double allPrice;                        //商品总价格
    private LinearLayout llRight;                         //返回按钮
    private TextView tvCancelPay;                       //取消结算

    private TextView tv_input;//输入
    private TextView tv_quick_choose;//快选
    private TextView tv_scan_code;//扫码

    private View view_input_underline;
    private View view_quick_choose_underline;
    private View view_scan_code_underline;

    public static Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                //刷新适配器I
                case 1:
                    Log.v("zyl", "刷新适配器");
                    if(goodsShowsAdapter!=null){
                        goodsShowsAdapter.notifyDataSetChanged();
                    }
                    computeGoodsAllPrices();
                    lvGoodsShows.setSelection(goodsShowsAdapter.getCount()-1);
                    break;
                case 2:
                    if(goodsShowsAdapter!=null){
                        goodsShowsAdapter.notifyDataSetChanged();
                    }
                    computeGoodsAllPrices();
                    break;
            }
        }
    };

    /**
     * 计算商品总价格
     */
    private static void computeGoodsAllPrices(){
        allPrice = 0;
        for (int i = 0; i<goodsListBeanList.size(); i++){
            GoodsListBean goodsListBean= goodsListBeanList.get(i);
            double singPrice = Double.parseDouble(goodsListBean.getPrice())*goodsListBean.getCount();
             allPrice += singPrice;
        }

        String allPriceStr  = MoneyUtil.formatMoney(allPrice+"");

        tvPayMoney.setText(allPriceStr+"");
        Log.v("zyl","allPrice:"+allPriceStr);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ExitApplication.getInstance().addActivity(this);
        setContentView(R.layout.addmerchandise);
        initFragment();
        initView();
        fm = getSupportFragmentManager();
        /*FragmentTransaction ft1 = fm.beginTransaction();
        ft1.replace(R.id.frag, keyboardFragment);
        ft1.commitAllowingStateLoss();*/

        changeTabUIAndFragment(0);

        goodsListBeanList.clear();
        handler.sendEmptyMessage(1);
        NetRequest netRequest = new NetRequest(this);
        //查询促销规则
        netRequest.requestStoreActivityPaymentFind(1);

    }


    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }
    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }
    public void initView(){

        lvGoodsShows = (ListView) findViewById(R.id.listcommodity);
        goodsShowsAdapter = new GoodsShowsAdapter(this,goodsListBeanList);
        lvGoodsShows.setAdapter(goodsShowsAdapter);
        tvPayMoney = (TextView) findViewById(R.id.pay_money);

        //结算
        findViewById(R.id.pay_affirm).setOnClickListener(this);

//        //挂单
//        findViewById(R.id.pay_hang_up).setOnClickListener(this);

        tvCancelPay = (TextView) findViewById(R.id.pay_cancel);
        tvCancelPay.setOnClickListener(this);

        findViewById(R.id.public_ll_return).setOnClickListener(this);
        TextView tvTitle = (TextView) findViewById(R.id.tvTitle);
        tvTitle.setText("收银台");
        findViewById(R.id.public_ll_right).setOnClickListener(this);
        tv_right= (TextView) findViewById(R.id.public_tv_right);
        tv_right.setText("设置");
        tv_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent =new Intent(CashierActivity.this,DeductionActivity.class);
                startActivity(intent);
            }
        });

        tv_input = (TextView) findViewById(R.id.tv_input);
        tv_quick_choose = (TextView) findViewById(R.id.tv_quick_choose);
        tv_scan_code = (TextView) findViewById(R.id.tv_scan_code);

        tv_input.setOnClickListener(this);
        tv_quick_choose.setOnClickListener(this);
        tv_scan_code.setOnClickListener(this);

        view_input_underline = findViewById(R.id.view_input_underline);
        view_quick_choose_underline =  findViewById(R.id.view_quick_choose_underline);
        view_scan_code_underline =  findViewById(R.id.view_scan_code_underline);

    }
    public void initFragment(){
        goodsFragment = new GoodsFragment();
        keyboardFragment = new KeyboardFragment();
        scanFragment = new ScanFragment();
        llChangeFragment =(TextView)findViewById(R.id.addmerchan_ll_change);
        llChangeFragment.setOnClickListener(this);
    }
    /**
     * 根据下标返回下一个fragment
     *
     * @return
     */
    public void replaceFragment() {
        switch (CurrentFragmentIndex%3) {
            //返回数字键盘Fragment
            case 0:
                FragmentTransaction ft1 = fm.beginTransaction();
                ft1.replace(R.id.frag,keyboardFragment);
                ft1.commitAllowingStateLoss();

                llChangeFragment.setBackgroundResource(R.drawable.icon_change_input1);
                break;
            //返回商品Fragment
            case 1:
                FragmentTransaction ft3 = fm.beginTransaction();
                ft3.replace(R.id.frag,scanFragment);
                ft3.commitAllowingStateLoss();
                llChangeFragment.setBackgroundResource(R.drawable.icon_change_scan1);
                break;
            //返回二维码Fragment
            case 2:
                FragmentTransaction ft2 = fm.beginTransaction();
                ft2.replace(R.id.frag,goodsFragment);
                ft2.commitAllowingStateLoss();
                llChangeFragment.setBackgroundResource(R.drawable.icon_change_select1);

                break;
            default:
                Log.v("zyl","点击了，非正常数字");
                break;
        }
        CurrentFragmentIndex++;
    }

    @Override
    public void finish() {
        Log.v("zyl","收银页面finish");
        super.finish();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            //切换不同视图
            case R.id.addmerchan_ll_change:
                Log.v("zyl","开始切换:"+CurrentFragmentIndex%3);
                replaceFragment();
                break;
            //返回
            case R.id.public_ll_return:
                finish();
                break;
//            case R.id.pay_hang_up:
//                break;
            case R.id.public_ll_right:
//                MobclickAgent.onEvent(CashierActivity.this,"005");
//                Intent intent0 = new Intent();
//                intent0.setClass(CashierActivity.this, AccountCheckingActivity.class);
//                intent0.putExtra("iscashiser",true);
//                startActivity(intent0);
                break;
            case R.id.tv_input:
                changeTabUIAndFragment(0);
                /*tv_input.setSelected(true);
                tv_quick_choose.setSelected(false);
                tv_scan_code.setSelected(false);
                CurrentFragmentIndex = 0;
                replaceFragment();*/
                break;
            case R.id.tv_quick_choose:
                changeTabUIAndFragment(1);
                /*tv_input.setSelected(false);
                tv_quick_choose.setSelected(true);
                tv_scan_code.setSelected(false);
                CurrentFragmentIndex = 2;
                replaceFragment();*/
                break;
            case R.id.tv_scan_code:
                changeTabUIAndFragment(2);
                /*tv_input.setSelected(false);
                tv_quick_choose.setSelected(false);
                tv_scan_code.setSelected(true);
                CurrentFragmentIndex = 1;
                replaceFragment();*/
                break;
            //点击结算
            case R.id.pay_affirm:
                if(Utils.isFastClick()){
                    return;
                }
                if(allPrice!=0){
                    Intent intent = new Intent();
                    double num = Double.parseDouble(MoneyUtil.formatMoney(allPrice + ""));
                    intent.putExtra("price_original",MoneyUtil.formatMoney(allPrice + "") );
                    if(num>2000){
                        Toast.makeText(CashierActivity.this,"结算金额不能大于2000！",Toast.LENGTH_SHORT).show();
                        return;
                    }
                    Log.v("zyl", "结算时候的金额：" +num);
                    intent.setClass(CashierActivity.this, SumNewActivity.class);
                    startActivity(intent);

                    FragmentTransaction ft1 = fm.beginTransaction();
                    ft1.replace(R.id.frag, keyboardFragment);
                    ft1.commitAllowingStateLoss ();

                    llChangeFragment.setBackgroundResource(R.drawable.icon_change_input1);
                    CurrentFragmentIndex=4;
                }else{
                    Toast.makeText(CashierActivity.this, "金额不能为0",
                            Toast.LENGTH_SHORT).show();
                }
                break;
            //点击取消结算
            case R.id.pay_cancel:
                goodsListBeanList.clear();
                handler.sendEmptyMessage(1);
                break;
        }
    }

    /**
     * 切换页签指示器和Fragment
     * @param index 点击的页签的索引
     */
    private void changeTabUIAndFragment(int index) {
        tv_input.setSelected(index == 0 ? true :false);
        tv_quick_choose.setSelected(index == 1 ? true :false);
        tv_scan_code.setSelected(index == 2 ? true :false);
        view_input_underline.setVisibility(index == 0 ? View.VISIBLE :View.GONE);
        view_quick_choose_underline.setVisibility(index == 1 ? View.VISIBLE :View.GONE);
        view_scan_code_underline.setVisibility(index == 2 ? View.VISIBLE :View.GONE);

        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        switch (index){
            case 0:
                ft.replace(R.id.frag,keyboardFragment);
                break;
            case 1:
                ft.replace(R.id.frag,goodsFragment);
                break;
            case 2:
                ft.replace(R.id.frag,scanFragment);
                break;
        }

        ft.commitAllowingStateLoss();
    }


    @Override
    public void onAfinalFail() {

    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
         if(requestId == 1){
            try{
                JSONArray jsonArray = new JSONArray(result);
                for(int i=0;i<jsonArray.length();i++){
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    String activity = jsonObject.getString("activity");
                    //满返
                    if(activity.equals("rebate")){
                        SettingData.moreRebate = jsonObject.getString("amount");
                        SettingData.moreRebateData = jsonObject.getString("promotion");
                        SettingData.rebateStatus = jsonObject.getString("status");
                    }
                    //折扣
                    if(activity.equals("discount")){
                        SettingData.discount = jsonObject.getString("promotion");
                        SettingData.discountStatus = jsonObject.getString("status");
                    }
                    //满送
                    if(activity.equals("reward")){
                        SettingData.moreReward = jsonObject.getString("amount");
                        SettingData.moreRewardData = jsonObject.getString("promotion");
                        SettingData.rewardStatus = jsonObject.getString("status");
                    }
                }
            }catch (Exception e){}
        }
    }

    @Override
    public void onExecuteFail(int requestId, String msg) {

    }
}
